package com.kdl.webconfig.controller;


import com.kdl.webconfig.vo.BasePageVO;
import com.kdl.webconfig.vo.BaseRespVO;
import com.kdl.webconfig.vo.PageVO;
import com.kdl.webconfig.business.CustomBusiness;
import com.kdl.webconfig.vo.config.CustomInfoVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * <p>
 * 客户信息表 前端控制器
 * </p>
 *
 * @author wcj
 * @since 2022-09-05
 */
@RestController
@RequestMapping("/webconfig/customInfo")
@Slf4j
@Api(value = "客户管理接口", tags = {"客户管理"})
public class CustomInfoController {

    @Resource
    private CustomBusiness customBusiness;

    @PostMapping("/page")
    @ApiOperation(value = "客户列表")
    public BaseRespVO<PageVO<CustomInfoVO>> page(@RequestBody@Valid BasePageVO basePageVO){
        PageVO<CustomInfoVO> page = customBusiness.page(basePageVO);
        return BaseRespVO.success(page);
    }

    @PostMapping("/delete/{id}")
    @ApiOperation(value = "客户删除")
    public BaseRespVO<Boolean> deleteById(@PathVariable Integer id){
        Boolean aBoolean = customBusiness.deleteById(id);
        return BaseRespVO.success(aBoolean);
    }

    /**
     * 表格生成器
     *
     * @param response
     */
    @GetMapping("/formGeneration")
    @ApiOperation(value = "客户导出")
    public void tableDowload(HttpServletRequest request,HttpServletResponse response) {
        log.info("开始生成表格数据");
        XSSFWorkbook xssfSheets = customBusiness.formGeneration();

        String fileName = "客户留资.xlsx";
        OutputStream outputStream = null;
        try {
            setResponseHeader(response,fileName);
            outputStream = new BufferedOutputStream(response.getOutputStream());
            xssfSheets.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*
       设置浏览器下载响应头
    */
    private static void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}

